package com.bolt.auth.security.auth.server.service.impl;

import com.bolt.auth.admin.api.feign.RemoteUserService;
import com.bolt.auth.admin.api.sys.dto.UserDTO;
import com.bolt.auth.admin.api.sys.dto.UserInfo;
import com.bolt.auth.security.auth.server.service.AuthUserDetailsService;
import com.bolt.auth.security.common.model.AuthUserDetails;
import com.bolt.convention.data.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class UserDetailServiceImpl implements AuthUserDetailsService {

    @Autowired
    private RemoteUserService remoteUserService;
    /**
     * 根据电话号码查询用户
     *
     * @param mobile
     * @return
     */
    @Override
    public UserDetails loadUserByMobile(String mobile) {
        return null;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ResultMessage<UserInfo> usrInfo = remoteUserService.findByUserName(username);

        return getUserDetails(usrInfo);
    }

    /**
     * 构建userdetails
     *
     * @param usrInfo 用户信息
     * @return
     */
    private AuthUserDetails getUserDetails( ResultMessage<UserInfo> usrInfo ) {

        if (usrInfo == null || usrInfo.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserInfo info = usrInfo.getData();
        AuthUserDetails authUserDetails = new AuthUserDetails();
        authUserDetails.setUserId(info.getUserId());
        authUserDetails.setUsername(info.getUserName());
        authUserDetails.setEnabled(info.getEnabled());
        authUserDetails.setPassword(info.getPassword());
        authUserDetails.setAuthSalt(info.getAuthSalt());
        authUserDetails.setSuperUser(info.getIsAdmin());

        authUserDetails.setPermissions(info.getPermissions());
        authUserDetails.setRoles(info.getRoles());
        return authUserDetails;
    }
}

 